
package com.winning.sx.microframework.controller.busi;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.winning.dapi.data.entity.DataTable;
import com.winning.sx.microframework.common.util.*;
import com.winning.sx.microframework.controller.base.QRcodeController;
import com.winning.sx.microframework.model.exception.CustomException;
import com.winning.sx.microframework.model.manage.LoginSession;
import com.winning.sx.microframework.model.message.AjaxDataResponseMessage;
import com.winning.sx.microframework.model.message.AjaxTableResponseMessage;
import com.winning.sx.microframework.service.EasyService;
import com.winning.sx.microframework.service.sysmanage.ConstService;
import com.winning.sx.microframework.service.sysmanage.RoleManageService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/busi/equipment/use")
public class EquipmentUseController {
    @Autowired
    EasyService easyService;
    @Autowired
    ConstService service;

    @RequestMapping(value = {"/", ""})
    public ModelAndView init() throws IOException, CustomException, SQLException {
        ModelAndView mv = new ModelAndView("/busi/equipmentUse");
        List state = service.queryCount("203");
        mv.addObject("state", state);
        Map eqRootClassP = new HashMap();
        eqRootClassP.put("superId", "0");
        eqRootClassP.put("validFlag", "100001");
        eqRootClassP.put("type", "301001");
        DataTable eqRootClassS = easyService.queryList("BASE_EqClass", eqRootClassP);
        List eqRootClass = eqRootClassS.getDataRows();
        mv.addObject("eqRootClass", eqRootClass);
        List brand = service.queryCount("300");
        mv.addObject("brand", brand);
        List secrecy = service.queryCount("116");
        mv.addObject("secrecy", secrecy);
        List useType = service.queryCount("108");
        mv.addObject("useType", useType);

        List warehouseList = easyService.querySql("select  *  from BASE_Warehouse  where  validFlag='100001' ", new HashMap()).getDataRows();
        mv.addObject("warehouseList", warehouseList);

        List staffList = easyService.querySql("select  *  from BASE_Staff   where  validFlag='100001' and organizationId in (" +
                " select id from BASE_Organization where organizationType='400001' " +
                ") ", new HashMap()).getDataRows();
        mv.addObject("staffList", staffList);
        //        Map map = new HashMap();
//        map.put("organizationType","400001");
//        List organizationName = easyService.querySql("select case when p.id is not null then p.name+'-'+o.name else o.name end name   ,o.id from BASE_Organization o  " +
//                "FULL join BASE_Organization p on o.superOrganizationId=p.id where o.id is not null and o.organizationType=:organizationType ", map).getDataRows();
        Map map = new HashMap();
        List eqClass = easyService.querySql("SELECT " +
                "  c1.name + '-' + c2.name name, " +
                "  c2.code " +
                "FROM BASE_EqClass c1 " +
                "  RIGHT JOIN BASE_EqClass c2 ON c1.id = c2.superId " +
                "WHERE c2.validFlag = '100001' AND c1.id IS NOT NULL ", map).getDataRows();
        mv.addObject("eqClass", eqClass);

//        List warehouseChangeList = easyService.querySql("SELECT top 50 * " +
//                " FROM BUSI_WarehouseChange c " +
//                " WHERE c.validFlag = '100001' order by id desc ", map).getDataRows();
//        mv.addObject("warehouseChangeList", warehouseChangeList);

        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        Map<String, String> param = new HashMap();
        param.put("organizationType", "400001");
        param.put("superOrganizationId", login.getSuperOrgId());
        mv.addObject("organizationName", JSON.toJSON(service.queryMyOrg(param)).toString());
        Map code = new HashMap();
        code.put("state", Constains.ACTIVE_FALSE);
        List QRcode = easyService.queryList("BASE_QRcode", code).getDataRows();
        mv.addObject("QRcode", QRcode);
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = {"/queryList"})
    public AjaxTableResponseMessage queryMessageList(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            Map paramNew = new HashMap();
            if (!"0".equals(param.get("type"))) {
                String code = param.get("type").toString().trim();
                paramNew.put("oneCode", code);
            }
            if (!"0".equals(param.get("useType"))) {
                String code = param.get("useType").toString().trim();
                paramNew.put("useType", code);
            }
            if (!"0".equals(param.get("brand"))) {
                String constType = param.get("brand").toString().trim();
                paramNew.put("brandCode", constType);
            }
            if ("0".equals(param.get("oneOrganization"))) {
                paramNew.put("organizationId", login.getSuperOrgId());
            } else {
                paramNew.put("organizationId", param.get("oneOrganization"));
            }
            Map orgParam = new HashMap();
            orgParam.put("superOrganizationId", paramNew.get("organizationId").toString());
            orgParam.put("organizationType", "400001");
            String orgs = service.queryMyOrg(orgParam).get("orgs").toString();
            if (orgs.length() == 0) {
                orgs = paramNew.get("organizationId").toString();
            } else {
                orgs += ("," + paramNew.get("organizationId").toString());
            }
            if (!"".equals(param.get("name").trim()) && param.get("name").trim() != null) {
                paramNew.put("name", param.get("name").trim());
            }
            paramNew.put("b_createTime", param.get("b_createTime"));
            paramNew.put("e_createTime", param.get("e_createTime"));
            String sql = "select eg.useStaffId,eg.useType, wc.flowCode changeCode,wc.warehouseId,wc.type changeType, e.*,s2.name useStaffName,o.name organizationName,c.name type,co.name brand,q.code QRcode,s.name createName,s1.name updateName,e.model model  from BASE_Equipment e " +
                    "left join BASE_Organization o on o.id=e.organizationId " +
                    "left join BASE_Const c on c.code =e.oneCode  " +
                    "left join BASE_Const co on co.code=e.brandCode " +

                    "left join BUSI_WarehouseChange wc on wc.id =e.changeId  " +
                    "left join BUSI_EquipmentGetDetail egd on wc.getDetailId =egd.id  " +
                    "left join BUSI_EquipmentGet eg on egd.getId =eg.id  " +
                    "left join BASE_Staff s2 on s2.id=eg.useStaffId " +

                    "left join BASE_Staff s on s.id=e.inputStaffId " +
                    "left join BASE_Staff s1 on s1.id=e.updateStaffId " +
                    "left join BASE_QRcode q on q.id=e.QRCode where 1=1 and e.validFlag=100001 " +
                    (paramNew.get("oneCode") != null ? (" and e.oneCode like '" + paramNew.get("oneCode") + "%'") : "") +
                    (paramNew.get("brandCode") != null ? (" and e.brandCode='" + paramNew.get("brandCode") + "'") : "") +
                    (paramNew.get("useType") != null ? (" and eg.useType='" + paramNew.get("useType") + "'") : "") +
                    (paramNew.get("organizationId") != null ? (" and e.organizationId in (" + orgs + ")") : "") +
                    (paramNew.get("useStaffId") != null ? (" and e.useStaffId =" + paramNew.get("useStaffId")) : "") +
                    (paramNew.get("name") != null ? " and( e.model like :name+'%' or q.code like :name+'%' or e.barCode like :name +'%') " : "") +
                    (paramNew.get("b_createTime") != null ? (" and e.createTime>='" + paramNew.get("b_createTime") + "'") : "") +
                    (paramNew.get("e_createTime") != null ? (" and e.createTime<='" + paramNew.get("e_createTime") + "'") : "") +
                    " order by createTime desc";
            DataTable all = easyService.querySql(sql, paramNew);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/save"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage insert(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            if (login.getRoles() != null) {
                //后台登录那就给权限吧。暂时不进行判断了
            } else if (login.getRoleId().equals("0")) {
                ajaxDataResponseMessage.setSuccess(false);
                ajaxDataResponseMessage.setErrorMsg("操作失败：权限不足！");
                return ajaxDataResponseMessage;
            }
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                easyService.NotNull(map, new String[]{
                        "organizationId",
                        "usePosition",
                        "useStaffId",
                        "useType",
                        "buyTime",
                        "useType",
                        "oneCode",
                        "brandCode",
                        "modelId"
//                        ,"barCode"
                }, new String[]{
                        "使用机构",
                        "使用位置",
                        "使用人",
                        "使用方式",
                        "领用时间",
                        "使用位置",
                        "产品类型",
                        "品牌",
                        "型号"
//                        ,"条形码"
                });
                Map param = new HashMap();
                Map eqClassParam = new HashMap();
                eqClassParam.put("code", map.get("oneCode").toString());
                Map eqClass = easyService.queryEntity("Base_EqClass", eqClassParam);
                String type = eqClass.get("name").toString();
                String constType = map.get("brandCode").toString().trim();
                List constEntity = service.query(constType);
                Map constParam = (Map) constEntity.get(0);
                String brand = constParam.get("name").toString();
                if (!"".equals(map.get("externalPhotos"))) {
                    //图片流生成文件返回文件地址
                    param.put("externalPhotos", FileTools.saveImage("equipmentPic", map.get("externalPhotos")));
                }
                if (!"".equals(map.get("nameplatePhoto"))) {
                    //图片流生成文件返回文件地址
                    param.put("nameplatePhoto", FileTools.saveImage("equipmentNamePic", map.get("nameplatePhoto")));
                }
                //查询资产明细表
                if (map.get("modelId").toString().equals("-1")) {
                    Map newModel = new HashMap();
                    newModel.put("name", map.get("newModel").toString());
                    newModel.put("state", Constains.EQMODEL_STATE_2);
                    newModel.put("type", map.get("oneCode"));
                    newModel.put("brand", map.get("brandCode"));
                    newModel.put("image", param.get("externalPhotos"));
                    newModel.put("pym", Tools.getFirstSpell(map.get("newModel").toString()));
                    easyService.save("BASE_EquipmentDetail", "id", newModel);
                    map.put("modelId", newModel.get("id").toString());
                }
                String model = map.get("model").toString();
                param.put("model", model);
                param.put("name", type + "-" + brand + "-" + model);

                if ("".equals(map.get("id").toString())) {
                    param.put("inputStaffId", login.getStaffId().toString());
                } else {
                    param.put("updateStaffId", login.getStaffId().toString());
                }
                //动态生成二维码
                if (map.get("QRCode").toString().equals("-1")) {
                    Map qrCode = new HashMap();
                    qrCode.put("state", "500001");
                    qrCode.put("code", QRcodeController.createValCode(12));
                    easyService.save("BASE_QRcode", "id", qrCode);
                    param.put("QRCode", qrCode.get("id").toString());
                } else {
                    param.put("QRCode", map.get("QRCode"));
                }
                param.put("modelId", map.get("modelId").toString());
                param.put("changeId", saveEquipmentGetInfo(map));
                String oneOrganization = map.get("organizationId").toString().replaceAll(",", "");
                param.put("organizationId", oneOrganization);
                param.put("usePosition", map.get("usePosition"));
                param.put("oneCode", map.get("oneCode"));
                param.put("configurationDescription", map.get("configurationDescription"));
                param.put("brandCode", map.get("brandCode"));
                param.put("barCode", map.get("barCode"));
                if (map.get("secrecy") == null) param.put("secrecy", Constains.SECRET_ONE);
                else param.put("secrecy", map.get("secrecy"));
                param.put("buyTime", map.get("buyTime"));

                param.put("staffId", map.get("useStaffId").toString());
                param.put("useType", map.get("useType").toString());
                param.put("certCode", map.get("certCode").toString());

                if (!"".equals(map.get("id").toString())) {
                    param.put("id", map.get("id").toString());
                } else {
                    //新增附加状态，修改不能加状态
                    param.put("state", Constains.Equipment_state_edit);
                }
                easyService.save("BASE_Equipment", "id", param);
                //查询有没有最近的未确认的资产变动信息，如果有就跳过，如果没有则加入一条待确认的变动记录

                String sql = "select r.* from BUSI_EquipmentChange r " +
                        " where r.eId='" + param.get("id").toString() + "' and validFlag='100001' and type='123009' and state in ('334001') order by r.createTime desc";
                DataTable changeInfo = easyService.querySql(sql, new HashMap<>());
                if (changeInfo.getTotalRowNum() == 0) {
                    Map eChangeInfo = new HashMap();
                    eChangeInfo.put("eId", param.get("id").toString());
                    eChangeInfo.put("type", "123009");
                    eChangeInfo.put("flowCode", FlowCodeUtil.getFlowCode());
                    eChangeInfo.put("state", "334001");
                    eChangeInfo.put("createStaffId", login.getStaffId().toString());

                    eChangeInfo.put("fId", param.get("changeId").toString());
                    eChangeInfo.put("newOrg", oneOrganization);
                    eChangeInfo.put("newStaff", map.get("useStaffId").toString());
                    eChangeInfo.put("newPosition", map.get("usePosition").toString());
                    eChangeInfo.put("newUseType", map.get("useType").toString());
                    easyService.save("BUSI_EquipmentChange", "id", eChangeInfo);
                } else {
                    Map eChangeInfo = changeInfo.getDataRows().get(0);
                    easyService.ChangeBeanToStringMap(eChangeInfo);
                    eChangeInfo.put("fId", param.get("changeId").toString());
                    eChangeInfo.put("newOrg", oneOrganization);
                    eChangeInfo.put("newStaff", map.get("useStaffId").toString());
                    eChangeInfo.put("newPosition", map.get("usePosition").toString());
                    eChangeInfo.put("newUseType", map.get("useType").toString());
                    eChangeInfo.put("source", map.get("source").toString());
                    eChangeInfo.put("updateStaffId", login.getStaffId().toString());
                    easyService.save("BUSI_EquipmentChange", "id", eChangeInfo);
                }
                Map QRcode = new HashMap();
                QRcode.put("id", map.get("QRCode"));
                Map QRcodeEntity = easyService.queryEntity("BASE_QRcode", QRcode);
                if (QRcodeEntity != null) {
                    Map state = new HashMap();
                    state.put("state", "500001");
                    state.put("activeTime", SqlTool.getNowTimeString());
                    easyService.update("BASE_QRcode", QRcode, state);
                }
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    /***
     * 生成申请，明细，返回出库单id
     * @param param
     * @return
     */
    public String saveEquipmentGetInfo(Map param) throws Exception {
        /***
         * 可以出库单生成，但是不允许产生库存的真实修改，没有意义。保留出库单即可
         */
        Map getInfo = new HashMap();
        Map getDetailInfo = new HashMap();
        Map changeInfo = new HashMap();
        if (param.get("changeId") != null && (!"".equals(param.get("changeId")))) {
            Map pc = new HashMap();
            pc.put("id", param.get("changeId").toString());
            changeInfo = easyService.queryEntity("BUSI_WarehouseChange", pc);
            //除了初始化的数据，不允许修改出库单
            if (!changeInfo.get("type").toString().equals("333100")) return param.get("changeId").toString();
            pc.put("id", changeInfo.get("getDetailId").toString());
            getDetailInfo = easyService.queryEntity("BUSI_EquipmentGetDetail", pc);
            pc.put("id", getDetailInfo.get("getId").toString());
            getInfo = easyService.queryEntity("BUSI_EquipmentGet", pc);
        }
        if (param.get("warehouseId") == null || "-1".equals(param.get("warehouseId"))) {
            //通过资产类型查找仓库，默认选择所属机构下的仓库
            List warehouseList = easyService.querySql("select * from BASE_Warehouse w where w.id in ( " +
                    "  select d.warehouseId from BASE_WarehouseType d left join BASE_EqClass c on d.oneCode=c.code where c.id in ( " +
                    "    select c.superId from BASE_EqClass c where c.code='" + param.get("oneCode").toString() + "' " +
                    "  ) and d.validFlag='100001' " +
                    ") " +
                    "order by w.id desc;", new HashMap<>()).getDataRows();
            if (warehouseList.size() == 0) throw new Exception("没有找到此设备的仓库");
            param.put("warehouseId", ((Map) warehouseList.get(0)).get("id").toString());
        }
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        getInfo.put("useOrgId", param.get("organizationId").toString());
        getInfo.put("useStaffId", param.get("useStaffId").toString());
        getInfo.put("useType", param.get("useType").toString());
        getInfo.put("usePosition", param.get("usePosition").toString());
        getInfo.put("reason", "资产使用生成初始化申请单");
        getInfo.put("checkTime", param.get("buyTime").toString());
        getInfo.put("checkOrgId", login.getOrgId().toString());
        getInfo.put("checkStaffId", login.getStaffId().toString());
        getInfo.put("state", "109002");
        getInfo.put("warehouseId", param.get("warehouseId").toString());
        if (getInfo.get("flowCode") == null) getInfo.put("flowCode", FlowCodeUtil.getFlowCode());
        easyService.save("BUSI_EquipmentGet", "id", getInfo);
        getDetailInfo.put("getId", getInfo.get("id").toString());
        getDetailInfo.put("modelId", param.get("modelId").toString());
        getDetailInfo.put("getCount", "1");
        easyService.save("BUSI_EquipmentGetDetail", "id", getDetailInfo);
        changeInfo.put("getDetailId", getDetailInfo.get("id").toString());
        changeInfo.put("getId", getInfo.get("id").toString());
        changeInfo.put("type", "333100");
        changeInfo.put("warehouseId", param.get("warehouseId").toString());
        changeInfo.put("modelId", param.get("modelId").toString());
        changeInfo.put("count", "1");
        changeInfo.put("reason", "资产使用生成初始化出库变动单");
        if (changeInfo.get("flowCode") == null) changeInfo.put("flowCode", FlowCodeUtil.getFlowCode());
        changeInfo.put("state", "334002");
        easyService.save("BUSI_WarehouseChange", "id", changeInfo);
        return changeInfo.get("id").toString();
    }

    @ResponseBody
    @RequestMapping(value = {"/delete"})
    public AjaxDataResponseMessage delete(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                easyService.delete("BASE_Equipment", "id", map);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/queryModel"})
    public AjaxTableResponseMessage queryModel(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                Map param = new HashMap();
                param.put("type", map.get("oneCode"));
                param.put("brand", map.get("brandCode"));
                param.put("state", Constains.EQMODEL_STATE_1);
                DataTable all = service.queryModel(param);
                ajaxTableResponseMessage.setDatas(all.getDataRows());
                ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
                ajaxTableResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg(e.getMessage());
        }
        return ajaxTableResponseMessage;
    }
}

